package com.wider.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import javax.naming.LimitExceededException;
import javax.naming.SizeLimitExceededException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wider.servlet.multipart.MultipartFormData;

/**
 * Servlet implementation class EchoServlet
 */
public class EchoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EchoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*
		AppletHTML applet_html = new AppletHTML();
		applet_html.SetAppletClass("com.wider.applets.SimpleApplet");
		applet_html.SetAppletCodebase("./applet/");
		applet_html.SetAppletArchive("");
		applet_html.SetAppletSize(500, 300);
		applet_html.SetParameter("ServerURL", request.getRequestURL().toString());
		applet_html.EndOptions();
		
		PrintWriter rspndr = response.getWriter();
		rspndr.println("<HTML><HEAD><TITLE>Echo webapp</TITLE></HEAD><BODY>");
		rspndr.println("Hello! This is Echo webapp");
		rspndr.println(applet_html.toString());
		rspndr.println("</BODY></HTML>");
		*/

		System.out.println("歡迎使用 EchoServer");
		response.setCharacterEncoding("UTF-8");
		PrintWriter rspndr = response.getWriter();

		String command = (String) request.getParameter("command");
		
		if (null == command){
			rspndr.println("Hello");
			return;
		}
		
		System.out.println("command = " + command);
		
		if (command.equalsIgnoreCase("sleep")){
			long timeout = Long.parseLong(((String) request.getParameter("timeout")).toString().trim());
			try {
				System.out.println("Got command to sleep for " + timeout + " millis");
				Thread.sleep(timeout);
				System.out.println("wake up and response to client");
				rspndr.println("Slept for " + timeout + " millis.");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        // TODO Auto-generated method stub
            PrintWriter	rspndr			= null;
            MultipartFormData formdata	= null;
            
            try{
            	response.setCharacterEncoding("UTF-8");
            	
                rspndr      = response.getWriter();
                formdata    = new MultipartFormData(request);
				
                Iterator paramit = formdata.getParameterMap().entrySet().iterator();
                while(paramit.hasNext()){
                    Map.Entry<String, Object> param = (Map.Entry<String, Object>) paramit.next();
                    String paramkey = param.getKey();
                    Object paramval = param.getValue();
                    System.out.println("Parameter: " + paramkey + " : " + paramval);

                    if (paramval.getClass().getName() == Vector.class.getName()){
                        System.out.println("Found Vector.");
                        Vector<String> files = (Vector<String>) paramval;

                        int ret = 0;
                        ret = formdata.saveFiles(files, "./");
                        System.out.println("Files saved? " + ret);
                    }
                }
	            
                formdata.checkCompleteness();
                rspndr.write("Completed");
            }
            //The better way is to enumerate all possible exceptions and try to response to the client with the corresponding error code/message
            catch (SizeLimitExceededException e){
                response.setStatus(206);
                rspndr.write(e.getMessage());
            } catch (LimitExceededException e) {
                try {
                    response.sendError(413);
                } catch (IOException e1) {
                    //Non-reportable exception, dump stack trace
                    e1.printStackTrace();
                }
            } catch (IOException e){
                try {
                    response.sendError(500);
                } catch (IOException e1) {
                    //Non-reportable exception, dump stack trace
                    e1.printStackTrace();
                }
            }
	}

}
